import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, } from "react";
import { SelectBox } from "devextreme-react";
import { Input, Select } from "antd";
import { consts } from "../../../../../tools/consts";
import { SearchOutlined } from "@ant-design/icons";
import { CpasIcon, DevGrid } from "~/public/cpas-ui";
import { getReportData, } from "../../../classes/HandSonGridToolService/getDataSourceService";
import { getYears } from "../../../../../tools/Tools";
import { dbname } from "../../../classes/HandSonGridToolService/pubDbname";
import { getColumnHeader, getTableData, } from "./DataService";
import { DataGridOptions } from "./CommonOption";
import { devCellScrollPositionBySelected, devCellSelected, resetScrollView, } from "../../../classes/DevTableService";
export const WorkerPaperTabPanel = (props, ref) => {
    /**
     * 受控组件
     */
    const devTableRef = useRef(null);
    //取数源数据源
    const [sourceData, setSourceData] = useState([]);
    // 年度
    const yearData = consts.YearTagList;
    /**
     * 搜索条件
     */
    // 底稿名称
    const [searchWorkerPaperName, setSearchWorkerPapaerName] = useState("");
    // 取数源
    const [searchDataSource, setSearchDataSource] = useState("");
    // 年度
    const [searchYear, setSearchYear] = useState("");
    // 项目名称
    const projectSearchInputRef = useRef(null);
    // 公式坐标,目前仅会从父元素触发. 做状态回显,定位单元格. 当为null时说明没有选择公式，不需要定位
    const [formulaCoords, setFormulaCoords] = useState({
        tname: null,
        rmap: null,
        cmap: null,
        year: null,
    });
    const getProjectSearchValue = () => {
        return projectSearchInputRef.current?.input.value || "";
    };
    /**
     * 表体数据
     */
    const [workerPaperTableData, setWorkerPaperTableData] = useState({
        dataSource: [],
        columns: [],
    });
    /**
     * 数据源转换
     */
    const workerPaperData = useMemo(() => {
        return props.workePaperRawData.map((item) => {
            return { label: item.ReportItem, value: item.ReportItem };
        });
    }, [props.workePaperRawData]);
    /**
     * 初始化数据
     */
    useEffect(() => {
        if (props.workePaperRawData.length > 0) {
            if (props.itemName) {
                const itemFirst = props.itemName.split(",")[0];
                initSearchCondition(itemFirst);
            }
            else {
                initSearchCondition();
            }
        }
    }, [props.itemName, props.workePaperRawData]);
    const initSearchCondition = async (workerPaperName, source, year) => {
        // 如果传递了 workerPaperName 以传递的为准 , 否则走默认的第一个
        const defaultWorkerPaperName = workerPaperData.length > 0 ? workerPaperData[0].label : "";
        let selWorkerPaperName = workerPaperName
            ? workerPaperName
            : defaultWorkerPaperName;
        // 设置下拉框默认值
        setSearchWorkerPapaerName(selWorkerPaperName);
        // 初始化年度
        setSearchYear(year ? year : consts.ThisYear);
        // 更新联动
        await updateSourceData(selWorkerPaperName, source);
    };
    // 底稿名称 -> 取数源数据联动
    const updateSourceData = async (workerPaperName, source) => {
        let data = await getReportData(workerPaperName);
        const items = data.map((item) => {
            return { label: item.dataSrcName, value: item.dmName };
        });
        if (!items || items.length === 0) {
            // return msgError("没有获取到底稿 " + workerPaperName + " 的数据源列表.");
            return;
        }
        // 设置取数源数据
        setSourceData(items);
        const defaultSourceValue = items.length > 0 ? items[0].value : "";
        let searchDataValue = source || defaultSourceValue;
        // 设置取数源默认值
        setSearchDataSource(searchDataValue);
    };
    /**
     * 监听数据变化
     */
    // 同步2
    // 表格后台表格数据
    useEffect(() => {
        const devInstance = devTableRef?.current?.instance;
        if (searchYear &&
            searchDataSource &&
            props.activeKey === consts.WpTabKey &&
            devInstance) {
            updateTableData();
        }
    }, [searchYear, searchDataSource, formulaCoords, props.activeKey]);
    // 同步3
    // 根据公式,同步滚动条位置
    useEffect(() => {
        // dev bug 补丁 , 在开启虚拟化的情况下, 切换数据源必须重置表格的滚动条. 否则会出现白屏
        resetScrollView(devTableRef);
        if (formulaCoords.rmap &&
            formulaCoords.year === searchYear &&
            formulaCoords.tname === searchDataSource) {
            // 延时300更稳定, dev表格的渲染在收到useEffect,可能还没渲染完成. 这是dev自身的问题
            setTimeout(() => {
                devCellScrollPositionBySelected(devTableRef, formulaCoords.rmap, formulaCoords.cmap, workerPaperTableData, DataGridOptions.columnWidth);
            }, 300);
        }
    }, [workerPaperTableData, searchYear, searchDataSource]);
    // 同步4
    // 同步单元格选中状态
    const onContentReadyCallBack = useCallback(() => {
        if (formulaCoords.year === searchYear &&
            formulaCoords.tname === searchDataSource) {
            devCellSelected(devTableRef, formulaCoords.rmap, formulaCoords.cmap, DataGridOptions.columnWidth);
        }
    }, [formulaCoords, searchYear, searchDataSource]);
    useImperativeHandle(ref, () => {
        return {
            // 更新搜索条件状态
            updateSearchCondition: async (params) => {
                const { tname, year, source, rmap, cmap } = params;
                if (tname && source && year) {
                    // TODO 下拉框的取数源在外部传入 ,  useEffect props.workePaperRawData 可能会在该函数之后执行。 导致重新重置.
                    setTimeout(() => {
                        initSearchCondition(tname, source, year.toString());
                    }, 300);
                }
                setFormulaCoords({
                    rmap,
                    cmap,
                    year,
                    tname: source, //底稿结构化的表名是取数源下拉框内容, 不是表名
                });
            },
            // 获取当前取数源的表名
            getCurrentTName: () => {
                return searchDataSource;
            },
            // 获取当前年
            getCurrentYear: () => {
                return searchYear;
            },
        };
    });
    /**
     * 对外暴露函数
     */
    // 更新表格数据
    const updateTableData = async () => {
        const DataId = await getYears(searchYear);
        const params = {
            tname: searchDataSource,
            data_id: DataId,
            dbName: dbname,
            fields: [],
            where: "",
            order: "",
        };
        const projectSearchValue = getProjectSearchValue();
        const columns = await getColumnHeader(params);
        const dataSource = await getTableData(params, projectSearchValue);
        const tableData = {
            dataSource,
            columns: columns.columnData,
        };
        resetScrollView(devTableRef);
        setWorkerPaperTableData({ ...tableData });
    };
    /**
     * 事件
     */
    // 底稿名称下拉框
    const workerPaperSelectClick = async (e) => {
        const workerPaperName = e.itemData.value;
        // 设置底稿名称
        setSearchWorkerPapaerName(workerPaperName);
        // 更新联动取数源
        await updateSourceData(workerPaperName);
    };
    // 取数源下拉框
    const sourceDataSelectChange = (val, item) => {
        setSearchDataSource(val);
    };
    // 年度下拉框
    const yearDataSelectChange = (e) => {
        const yearValue = e.value;
        setSearchYear(yearValue);
    };
    // 项目回车
    const projectEnter = () => {
        updateTableData();
    };
    // 项目搜索
    const projectSearch = () => {
        updateTableData();
    };
    // 刷新
    const refresh = () => {
        updateTableData();
    };
    // devTable双击
    const devTableDbClick = useCallback((e) => {
        props.generateCustomFormula(e, searchDataSource, searchYear, "");
    }, [searchDataSource, searchYear]);
    return (_jsxs("div", { children: [_jsx("div", { style: { overflow: "auto", width: "100%" }, children: _jsxs("div", { className: "flexCon mb-10 f12", children: [_jsxs("div", { className: "flex-start", children: [_jsx("div", { className: "mr-8 nowrap", children: "\u5E95\u7A3F\u540D\u79F0:" }), _jsx("div", { className: "mr-8 custom_sel", id: "self_sty", children: _jsx(SelectBox, { placeholder: "\u9009\u62E9\u5E95\u7A3F\u540D\u79F0", noDataText: "\u65E0\u6570\u636E", searchEnabled: true, displayExpr: "label", valueExpr: "value", dataSource: workerPaperData, value: searchWorkerPaperName, onItemClick: workerPaperSelectClick, dropDownOptions: { width: "300px" } }) }), _jsx("div", { className: "mr-8 nowrap", children: "\u53D6\u6570\u6E90:" }), _jsx("div", { className: "mr-8 custom_sel", id: "self_sty", children: _jsx(Select, { value: searchDataSource, style: { width: 200 }, options: sourceData, onChange: sourceDataSelectChange }) }), _jsx("div", { className: "mr-8 nowrap", children: "\u5E74\u5EA6:" }), _jsx("div", { className: "custom_sel custom_curYear", children: _jsx(SelectBox, { width: 95, dataSource: yearData, value: searchYear, onValueChanged: yearDataSelectChange }) })] }), _jsxs("div", { className: "flex-start", children: [_jsx("div", { className: "mr-8 nowrap", children: "\u9879\u76EE\u540D\u79F0:" }), _jsx("div", { children: _jsx(Input, { style: { height: "30px" }, ref: projectSearchInputRef, size: "small", onPressEnter: projectEnter, placeholder: "", 
                                        // value={this.state.projectName2}
                                        suffix: _jsx(SearchOutlined, { onClick: projectSearch }) }) }), _jsx("div", { className: "icon_refresh", onClick: refresh, children: _jsx(CpasIcon, { type: "icon-yuefenzhongzhi" }) })] })] }) }), _jsx("div", { className: "h200", style: { overflow: "hidden" }, children: _jsx(DevGrid.RangeTap, { dataSource: workerPaperTableData.dataSource, columns: workerPaperTableData.columns, keyExpr: "主键", ref: devTableRef, scrolling: DataGridOptions.scrolling, paging: DataGridOptions.paging, showBorders: true, showRowLines: true, onContentReady: onContentReadyCallBack, 
                    // onContentReady={() => {
                    //   console.log(123);
                    // }}
                    onCellDblClick: devTableDbClick, columnWidth: DataGridOptions.columnWidth, rtlEnabled: false }) })] }));
};
const ForwardedWorkerPaperTabPanel = forwardRef(WorkerPaperTabPanel);
export default ForwardedWorkerPaperTabPanel;
